package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserDTO;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserDTO user){
        System.out.println("userDTO = " + user);
        UserVO u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            //用户名已存在
            return 2;
        }
        mapper.insert(user);
        return 1;
    }
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO user, HttpSession session, HttpServletResponse response){
        System.out.println("user = " + user );
        UserVO u = mapper.selectByUsername(user.getUsername());
        if(u !=null){
            if (user.getPassword().equals(u.getPassword())){
                //Session 对象中中保存对象user
             session.setAttribute("user",u);
             if(user.getRem()){
                 //创建cookie对象
                 Cookie c1= new Cookie("username", user.getUsername());
                 //设置时常
                 c1.setMaxAge(60*60*24*30);
                 Cookie c2= new Cookie("password", user.getPassword());

                 //把创建好的cookie发送到客户端
                 response.addCookie(c1);
                 response.addCookie(c2);

             }
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
